import moment from 'moment'
import Vue from 'vue'
import{gpMoveInfoPos} from '@/api/move'
import { gpFrontClick } from '@/api/front'
import { indexOfencodeURIComponent, goLogin } from './base'
import { msg } from './global-prototype'
import { dateFormat } from './functions.js'
import { gpUserInfos } from '@/api/user'
//报名跳转
export function onMainTitle(list, type = '12') {
  const index = list.filter((item, index) => {
    return item.type === type
  })
  return `/pages/interestActivity/interestActivity?type=${index[0].type}`
}
// 类型处理
function typeObjectKey(typeList) {
  const list = []
  const keys = Object.keys(typeList)
  keys.map((item) => {
    const title = typeList[item]
    const elegantType = item
    list.push({
      elegantType,
      title,
    })
  })
  return list
}

//风采
export function getElegantType() {
  const elegantType = {
    0: '热点关注',
    11: '最新动态',
    12: '视频直播',
  }
  return typeObjectKey(elegantType)
}

//视频直播
export function getLiveType() {
  const elegantType = {
    0: '风采视频',
    1: '直播活动',
  }
  return typeObjectKey(elegantType)
}
//阵地position
export function iconPositionList() {
  const path = `../../static/sub/`
  //front_from   传1-5 首页 来源
  // from_type传1～7 分类的 阵地类型
  //‘热门推荐’ ：column: 'front_clicktimes', order: 'desc'
  // '猜你喜欢'：column: 'front_recordtimes', order: 'desc'(已隐藏)
  const list = [
    {
      isTitleShow: false,
      title: '',
      list: [
        {
          img: `${path}service.png`,
          title: '党群服务',
          url: '/pages/partyGroupService/partyGroupService',
          type: 'service',
          value: '3',
          good: 4,
          show: true,
        },
        {
          img: `${path}station.png`,
          title: '爱心驿家',
          url: '/pages/partyGroupService/partyGroupService',
          type: 'station',
          value: '1',
          good: 5,
          show: true,
        },
        {
          img: `${path}active.png`,
          title: '活动中心',
          url: '/pages/partyGroupService/partyGroupService',
          type: 'emergency',
          value: '5',
          good: 6,
          show: true,
        },
        {
          img: `${path}emergency.png`,
          title: '救护站',
          url: '/pages/partyGroupService/partyGroupService',
          type: 'activity',
          value: '4',
          good: 7,
          show: true,
        },
        {
          img: `${path}mommy.png`,
          title: '妈咪小屋',
          url: '/pages/partyGroupService/partyGroupService',
          type: 'mommy',
          value: '2',
          good: 8,
          show: true,
        },
        {
          img: `${path}urbans.png`,
          title: '城管驿站',
          url: '/pages/partyGroupService/partyGroupService',
          type: 'urban',
          show: true,
          value: '6',
          good: 9,
        },
        {
          img: `${path}type.png`,
          title: '分类检索',
          url: '/pages/classificationSearch/classificationSearch',
          type: 'type',
          show: true,
        },
        {
          img: `${path}hot.png`,
          title: '热门推荐',
          url: '/pages/classificationSearch/classificationSearch',
          type: 'hot',
          show: true,
        },
        {
          img: `${path}like.png`,
          title: '猜你喜欢',
          url: '/pages/classificationSearch/classificationSearch',
          type: 'like',
          show: false,
        },
      ],
    },
  ]
  return list
}

//帮助
export function iconHelpList() {
  const path = `../../static/helpax/`
  const list = [
    {
      img: `${path}6e1bdec0a288fec4af4bd67073d9f23.png`,
      title: '我有金点子',
      url: '/pages/myHelp/myHelp',
      type: 'idea',
      index: 1,
      show: true,
    },
    {
      img: `${path}f37999c5dc7c0bba17b7cd854e2d597.png`,
      title: '我需要帮助',
      url: '/pages/myHelp/myHelp',
      type: 'help',
      index: 0,
      show: true,
    },
    {
      img: `${path}6962b0dc8f3219b3d71e4efb73407e7.png`,
      title: '我想要咨询',
      url: '/pages/myHelp/myHelp',
      type: 'advisory',
      index: 2,
      show: true,
    },
  ]
  return list
}
/**
 * @param { string } value
 * 验证手机号中国(严谨), 根据工信部2019年最新公布的手机号段

 */
export const isPhoneReg = (value) =>
  /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-7|9])|(?:5[0-3|5-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1|8|9]))\d{8}$/g.test(
    value
  )

/**
 * @param { string } value
 * 验证身份证码

 */
export const idCardReg = (value) =>
  /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/.test(
    value
  )

//计算经纬度数据
function getDistance(lat1, lon1, lat2, lon2) {
  const radLat1 = (lat1 * Math.PI) / 180 //将角度换算为弧度
  const radLat2 = (lat2 * Math.PI) / 180 //将角度换算为弧度
  const a = radLat1 - radLat2
  const b = (lon1 * Math.PI) / 180 - (lon2 * Math.PI) / 180
  let s =
    2 *
    Math.asin(
      Math.sqrt(
        Math.pow(Math.sin(a / 2), 2) +
          Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)
      )
    )
  s = s * 6378137.0 // 取WGS84标准参考椭球中的地球长半径(单位:m)
  return s
}
//距离我多少位置
export function getLatitudeLongitude(a, b, c, d) {
  if (!a || !b || !c || !d) {
    return 0
  }
  let len = getDistance(a, b, c, d)
  if (len < 1000) {
    len = len.toFixed(2) + 'm'
  } else {
    len = (len / 2 / 500).toFixed(2) + 'km'
  }
  return len
}
//跳转不同的分组url的id
export function getGroupUrlCb(cb, id, from) {
  var that = this
  gpFrontClick(id)
  cb(id)
    .then((res) => {
      if (res.success) {
        const url = res.result
        return indexOfencodeURIComponent(url)
      } else {
        msg(res.message)
        uni.navigateTo({
          url: `/pages/front/front?id=${id}`,
        })
      }
      //对url进行处理操作
      function getTimestampStr(str, start, end) {
        const res = str.match(new RegExp(`${start}(.*?)${end}`))
        return res ? res[1] : null
      }
    })
    .catch((e) => {
      msg(e.message)
    })
}
//根据来源跳页面
export function getFrontFrom(cb, id, frontFrom = '3', frontUrl = '', value = '1') {
  if (frontFrom !== '3') {
    if (frontUrl.includes('https://zdyy.hzgsredcross.org.cn')) {
      return getGroupUrlCb(cb, id, frontFrom)
    }
    if (!id) return false
    uni.navigateTo({
      url: `/pages/front/front?id=${id}&value=${value}`,
    })
  } else {
    return getGroupUrlCb(cb, id, frontFrom)
  }
}

/**
 * @author 2U
 * @param {Number} dateStatus
 * @param {Boolean} isFullPeople
 * @description  获取福利活动状态
 * @date {2021.09.01}
 */
export function getWelfareStatus(dateStatus, isFullPeople) {
  let data = {}
  if (dateStatus === 1) {
    data = {
      cls: 'status1',
      name: '抢福利中',
      btnName: '抢福利',
      status: dateStatus,
    }
    // 人数满的优先级 > 抢福利中
    if (isFullPeople) {
      data = {
        cls: 'status3',
        name: '福利已抢完',
        btnName: '福利已抢完',
        status: dateStatus,
      }
    }
  }
  if (dateStatus === 2) {
    data = {
      cls: 'status2',
      name: '福利兑换中',
      status: dateStatus,
    }
    // 人数满的优先级 > 福利兑换中
    if (isFullPeople) {
      data = {
        cls: 'status3',
        name: '福利已抢完',
        status: dateStatus,
      }
    }
  }
  if (dateStatus === 3) {
    data = {
      cls: 'status3',
      name: '活动已结束',
      status: dateStatus,
    }
  }
  if (dateStatus === 4) {
    data = {
      cls: 'status4',
      name: '预约未开始',
      status: dateStatus,
    }
  }
  if (dateStatus === 5) {
    data = {
      cls: 'status5',
      name: '预约已结束',
      status: dateStatus,
    }
  }
  return data
}
/**
 * @author 2U
 * @param {Number} dateStatus
 * @param {Boolean} isFullPeople
 * @description  获取组织活动状态
 * @date {2021.09.02}
 */
export function getOrganizationalStatus(dateStatus, isFullPeople) {
  let data = {}
  if (dateStatus === 1) {
    data = {
      cls: 'status1',
      name: '可预约',
      status: dateStatus,
    }
    // 人数满的优先级 > 抢福利中
    if (isFullPeople) {
      data = {
        cls: 'status3',
        name: '预约已满',
        status: dateStatus,
      }
    }
  }
  if (dateStatus === 2) {
    data = {
      cls: 'status2',
      name: '进行中',
      status: dateStatus,
    }
    // 人数满的优先级 > 福利兑换中
    if (isFullPeople) {
      data = {
        cls: 'status3',
        name: '预约已满',
        status: dateStatus,
      }
    }
  }
  if (dateStatus === 3) {
    data = {
      cls: 'status3',
      name: '活动已结束',
      status: dateStatus,
    }
  }
  if (dateStatus === 4) {
    data = {
      cls: 'status4',
      name: '预约未开始',
      status: dateStatus,
    }
  }
  if (dateStatus === 5) {
    data = {
      cls: 'status5',
      name: '预约已结束',
      status: dateStatus,
    }
  }
  return data
}

//获取活动状态--通用
export function getdateStatus(dateStatus) {
  return {
    1: '可预约',
    2: '进行中',
    3: '已结束',
    4: '预约未开始',
    5: '预约已截止',
  }[dateStatus]
}
//获取活动状态
export function getdateStatus8(dateStatus) {
  return {
    1: '可预约',
    2: '进行中',
    3: '已结束',
    4: '活动未开始',
    5: '活动已截止',
  }[dateStatus]
}
//是否过期时间
export function getDatePd(date) {
  if (!date) {
    return false
  }

  const endtime = new Date(Date.parse(date))
  //console.log('////',dateFormat(endtime,"yyyy-MM-dd hh:mm:ss"));
  const xdate = new Date()
  if (xdate > endtime) {
    return false
  } else {
    return true
  }
}
//获取动态时间
export function getUpdateDate(e) {
  return dateFormat(new Date(e.replace(/\-/g, '/')), 'yyyy-MM-dd hh:mm')
}

//计算经纬度位置
export function getLongitudeLatitude(list) {
  return list.map((item) => {
    const jv = parseInt(item.distance) || 0
    let text
    if (jv >= 1000) text = (jv / 1000).toFixed(2) + 'km'
    else text = jv + 'm'
    return text
  })
}
//获取图片相关信息
export function getImage(e) {
  if (e.indexOf('http') != -1) {
    return e
  } else {
    return process.uniEnv.imageUrl + e
  }
}
//群团状态
export function getgpinfoapplyStatus(a) {
  let str = ''
  const status = +a
  switch (status) {
    case 1:
      str = '未审核'
      break
    case 2:
      str = '审核中'
      break
    case 3:
      str = '审核通过'
      break
    case 4:
      str = '审核未通过'
      break
    case '':
      str = '未审核'
      break
  }
  return str
}
//是否可以 报名或者预约
export function isMoveStatus(dateStatus, type) {
  let data = {}
  if (dateStatus === 1) {
    data = {
      cls: 'status1',
      name: type === 1 ? '我要报名' : '可预约',
      status: dateStatus,
    }
  }
  if (dateStatus === 2) {
    data = {
      cls: 'status2',
      name: '预约进行中',
      status: dateStatus,
    }
  }
  if (dateStatus === 3) {
    data = {
      cls: 'status3',
      name: '预约已结束',
      status: dateStatus,
    }
  }
  if (dateStatus === 4) {
    data = {
      cls: 'status4',
      name: '预约未开始',
      status: dateStatus,
    }
  }
  if (dateStatus === 5) {
    data = {
      cls: 'status5',
      name: '预约已截止',
      status: dateStatus,
    }
  }
  return data
}
//获取身份证相关信息
export function getAnalyzeIDCard(IDCard) {
  const sexAndAge = {}
  //获取用户身份证号码
  const userCard = IDCard
  //如果身份证号码为undefind则返回空
  if (!userCard) {
    return sexAndAge
  }
  //获取性别
  if (parseInt(userCard.substr(16, 1)) % 2 == 1) {
    sexAndAge.sex = '男'
  } else {
    sexAndAge.sex = '女'
  }
  //获取出生年月日
  //userCard.substring(6,10) + "-" + userCard.substring(10,12) + "-" + userCard.substring(12,14);
  const yearBirth = userCard.substring(6, 10)
  const monthBirth = userCard.substring(10, 12)
  const dayBirth = userCard.substring(12, 14)
  //获取当前年月日并计算年龄
  const myDate = new Date()
  const monthNow = myDate.getMonth() + 1
  const dayNow = myDate.getDay()
  let age = myDate.getFullYear() - yearBirth
  if (monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)) {
    age--
  }
  //得到年龄
  sexAndAge.age = age || 0
  //返回性别和年龄
  return sexAndAge
}
//点击一次添加一次
export function addPlayVideoCb(cb, e) {
  const {
    target: {
      dataset: { videoid: videoId },
    },
  } = e
  const params = {
    category: '1',
    videoId,
  }
  cb(params)
    .then((res) => {})
    .catch((e) => {})
}

//新闻时间多少天
export function createTime_begin(day = 2) {
  const createTime_begin = moment().subtract(day, 'd').format('YYYY-MM-DD') //前3天
  return createTime_begin
}
//跳转地址
export function agetGroupUrls(cb, id, sceneName) {
  cb(id).then((res) => {
    const { code, message } = res
    if (code === 401) {
      goLogin()
      return
    }
    if (code === 500) {
      msg(message)
      return
    }
    if (res.success) {
      return indexOfencodeURIComponent(res.result, sceneName)
    }
  })
}

//福利活动状态
export const statusIsTimestampDuration = ({ datestartTime, dateendTime }) => {
  const astring = moment().valueOf() //当前系统时间
  const startTime = moment(datestartTime).valueOf()
  const endTime = moment(dateendTime).valueOf()
  const isTimestampDuration = moment.duration(startTime - astring).as('seconds')
  const endTimes = moment.duration(endTime - astring).as('seconds')
  //先判断当前时间与活动开始时间是否大于0
  if (isTimestampDuration > 0) {
    return {
      start: -1,
      value: '活动未开始',
    }
  } else {
    if (endTimes >= 0) {
      return {
        start: 1,
        value: '活动进行中',
      }
    } else {
      return {
        start: 0,
        value: '活动已结束',
      }
    }
  }
}

//获取用户信息
export const getIsTokenAndInfo = () => {
  return new Promise((resolve, reject) => {
    gpUserInfos()
      .then((res) => {
        if (res.success) {
          resolve(res)
        }
      })
      .catch((e) => {
        reject(e)
        goLogin()
      })
  })
}

//活动详情
export const onEventDetails = ({ activityCategory, id }, type = '699') => {
  //activityCategory 1是普通活动  2是福利活动
  if (type === '699') {
    if (activityCategory === 1) {
      uni.navigateTo({
        url: `/pages/activityDetail/activityDetail?id=${id}&values=1`,
      })
    } else if (activityCategory === 2) {
      uni.navigateTo({
        url: `/pages/grabBenefits/grabBenefits?id=${id}&values=1`,
      })
    } else {
      uni.navigateTo({
        url: `/pages/livePreview/livePreview?id=${id}&values=1`,
      })
    }
  } else {
    uni.navigateTo({
      url: `/pages/livePreview/livePreview?id=${id}&type=livePreview`,
    })
  }
}
export function onRouterLinkClick(url1) {
  let url = ''
  if (!url1.includes('http') || !url1.includes('http')) {
    url = '/pages/webview/webview?url=' + encodeURIComponent(`https://${url1}`)
  } else {
    url = '/pages/webview/webview?url=' + encodeURIComponent(url1)
  }
  uni.navigateTo({
    url,
  })
}


export function gpMoveInfoPosValue(param){
  return new Promise((resolve, reject) => {
    gpMoveInfoPos(param).then(res=>{
      if(res.code===200){
        resolve(res.result)
      } else {
        reject(res)
      }
    })
  })
}
//查询想要的数据
export function getGroupsCategoryList(arrList){
  const data = arrList
  let map = {},
    list = [];
  const call=Object.prototype.toString.call(data)
  if( data.length){
    data.map(item=>{
      if(!map[item.category]){
        list.push({
          Group: item.category,
          id:item.id,
          category:item.category,
          leftName:item.categoryName,
          navList: [item]
        });
        map[item.category] = item;
      }else{
        list.map(j=>{
          const dj = j;
          if(dj.category == item.category){
            dj.navList.push(item);
          }
        })
      }
    })
    return  list

  }


}

